package com.linzm.leetcode.primary.exercises1_20230114;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @Author zimingl
 * @Date 2023/1/15 2:10
 * @Description: 按奇偶性交换后的最大数字
 * 给你一个正整数 num 。你可以交换 num 中 奇偶性 相同的任意两位数字（即，都是奇数或者偶数）。
 * 返回交换 任意 次之后 num 的 最大 可能值。
 *
 * 做法：
 */
public class Demo13_2231 {
    public static void main(String[] args) {
//        int num = 1234;
        int num = 65875;
        Demo13_2231 demo13_2231 = new Demo13_2231();
        int i = demo13_2231.largestInteger2(num);
        System.out.println(i);
    }

    private int largestInteger(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        List<Integer> list11 = new ArrayList<>();
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list22 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        for (int i = 0; i < chars.length; i++) {
            if ((chars[i] - 48) % 2 != 0) {
                list1.add(i);
                list11.add((int) chars[i]);
            } else {
                list2.add(i);
                list22.add((int) chars[i]);
            }
        }
        int[] ints1 = list11.stream().sorted(Comparator.reverseOrder()).mapToInt(x -> x).toArray();
        for (int j = 0; j < list1.size(); j++) {
            chars[list1.get(j)] = (char) ints1[j];
        }
        int[] ints2 = list22.stream().sorted(Comparator.reverseOrder()).mapToInt(x -> x).toArray();
        for (int j = 0; j < list2.size(); j++) {
            chars[list2.get(j)] = (char) ints2[j];
        }
        String res = "";
        for (int i = 0; i < chars.length; i++) {
            res = res + chars[i];
        }
        return Integer.parseInt(res);
    }

    private int largestInteger2(int num) {
        char[] chars = String.valueOf(num).toCharArray();
        for (int i = 0; i < chars.length - 1; i++) {
            for (int j = i + 1; j < chars.length; j++) {
                if ((chars[i] - 48 - chars[j] - 48) % 2 == 0 && (chars[i] - 48) <  (chars[j] - 48)) {
                    swap(chars, i, j);
                }
            }
        }
        String res = "";
        for (int i = 0; i < chars.length; i++) {
            res = res + chars[i];
        }
        return Integer.parseInt(res);
    }

    private void swap(char[] arr, int index1, int index2) {
        char tmp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = tmp;
    }

    private boolean isSame(char a, char b) {
        if ((a - 48) % 2 == 0 && (b - 48) % 2 == 0) {
            return true;
        }
        if ((a - 48) % 2 != 0 && (b - 48) % 2 != 0) {
            return true;
        }
        return false;
    }
}
